package top.italks.demo.service.impl;

import top.italks.demo.entity.HREntity;
import top.italks.demo.entity.OrderEntity;
import top.italks.demo.mapper.OrderMapper;
import top.italks.demo.service.HRService;
import top.italks.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author 王少辉
 * @date 2019/9/7 14:59
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HRService hrService;

    @Override
    public OrderEntity createOrder(HREntity hr, BigDecimal amount, Integer purchaseDays, Integer purchaseNumber) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(UUID.randomUUID().toString().replaceAll("-", ""));
        orderEntity.setHrId(hr.getHrId());
        orderEntity.setAmount(amount);
        orderEntity.setPurchaseDays(purchaseDays);
        orderEntity.setPurchaseNumber(purchaseNumber);
        orderEntity.setStatus(0);
        orderEntity.setCreateTime(new Date());
        orderMapper.insert(orderEntity);
        return orderEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int confirmOrder(String outTradeNo) {
        OrderEntity orderEntity = orderMapper.queryByOrderId(outTradeNo);
        if (null != orderEntity) {
            HREntity hr = hrService.getHR(orderEntity.getHrId());
            hr.setRemainingCount(hr.getRemainingCount() + orderEntity.getPurchaseNumber());
            Calendar ca = Calendar.getInstance();
            ca.setTime(hr.getMemberValidity() == null ? new Date() : hr.getMemberValidity());
            ca.add(Calendar.DATE, orderEntity.getPurchaseDays());
            hr.setMemberValidity(ca.getTime());
            hrService.updateHR(hr);
            return orderMapper.confirmOrder(outTradeNo);
        }
        return 0;
    }

    @Override
    public int checkOrderStatus(String orderId) {
        return orderMapper.checkOrderStatus(orderId);
    }
}
